//
//  CALayer+Extension.swift
//  LiveTrivia
//
//  Created by 李响 on 2018/4/23.
//  Copyright © 2018年 LiveTrivia. All rights reserved.
//

import UIKit

extension CALayer {
    
    func toImage(scale: CGFloat = UIScreen.main.scale) -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, false, scale)
        render(in: UIGraphicsGetCurrentContext()!)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    func toColor(point: CGPoint) -> UIColor {
        
        var pixel = [UInt8](repeatElement(0, count: 4))
        let colorSpace = CGColorSpaceCreateDeviceRGB()
        let bitmapInfo = CGBitmapInfo(rawValue: CGImageAlphaInfo.premultipliedLast.rawValue)
        let context = CGContext(data: &pixel,
                                width: 1,
                                height: 1,
                                bitsPerComponent: 8,
                                bytesPerRow: 4,
                                space: colorSpace,
                                bitmapInfo: bitmapInfo.rawValue)
        if let context = context {
            
            context.translateBy(x: -point.x, y: -point.y)
            
            render(in: context)
            
            let r = pixel[0]
            let g = pixel[1]
            let b = pixel[2]
            let a = pixel[3]
            return UIColor(red: CGFloat(r)/255.0,
                           green: CGFloat(g)/255.0,
                           blue: CGFloat(b)/255.0,
                           alpha: CGFloat(a)/255.0)
        }
        return .clear
    }
}
